package com.easyaccount.service;

import com.easyaccount.bean.LoginUser;
import com.easyaccount.bean.UserVO;
import com.easyaccount.commons.CommonResp;
import com.easyaccount.commons.TablePage;
import com.easyaccount.dao.DeptMapper;
import com.easyaccount.dao.RoleMapper;
import com.easyaccount.dao.UserMapper;
import com.easyaccount.dao.UserRoleMapper;
import com.easyaccount.exception.BizException;
import com.easyaccount.model.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserProfileService {
    @Resource
    private MenuService menuService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;

    public CommonResp updateUser(LoginUser loginUser, HttpSession session){
        User user = new User();
        BeanUtils.copyProperties(loginUser,user);
        int i = userMapper.updateByPrimaryKeySelective(user);
        if(i > 0){
            Role role = getRole(user.getId());
            loginUser.setRole(role);
            List<Menu> menus = menuService.getMenu(user.getId());
            loginUser.setMenus(menuService.toTree(menus));
            session.setAttribute("user",loginUser);
            return CommonResp.success(loginUser);
        }else{
            return CommonResp.failed("更新失败",444);
        }
    }

    private Role getRole(Integer userId){
        UserRole userRole = userRoleMapper.selectByUserId(userId);    // 通过userid获取roleid
        Role role = roleMapper.selectByPrimaryKey(userRole.getRoleId());    // 通过roleid获取role
        return role;
    }
}
